package weifei.wx.community.controller;


import com.auth0.jwt.JWT;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import weifei.web.Result;
import weifei.wx.community.entity.TieCommentReply;
import weifei.wx.community.entity.TieCommentReplyNotice;
import weifei.wx.community.mapper.TieCommentMapper;
import weifei.wx.community.mapper.TieCommentReplyMapper;
import weifei.wx.community.mapper.TieCommentReplyNoticeMapper;

@RestController
@RequestMapping("/tie/comment/reply")
public class TieCommentReplyController
{

    @Autowired
    private TieCommentMapper tieCommentMapper;
    @Autowired
    private TieCommentReplyMapper tieCommentReplyMapper;
    @Autowired
    private TieCommentReplyNoticeMapper tieCommentReplyNoticeMapper;


    @PostMapping("/publish")
    public Result publish(
            HttpServletRequest request,
            @Valid @RequestBody TieCommentReply reply
        )
    {
        String token = request.getHeader("access_token");
        Long uid = JWT.decode(token).getClaim("user_id").asLong();

        QueryWrapper queryWrapper = QueryWrapper.create()
                .select()
                .where("id = ?", reply.getTieCommentId());
        var comment = this.tieCommentMapper.selectOneByQuery(queryWrapper);
        if (comment == null)
            return Result.failed("不存在的评论");

        reply.setUserId(uid);
        if (this.tieCommentReplyMapper.insert(reply) == 0)
            return Result.failed("数据库错误");

        queryWrapper = QueryWrapper.create()
                .select()
                .orderBy("id desc")
                .where("content = ?", reply.getContent());
        var r = this.tieCommentReplyMapper.selectOneByQuery(queryWrapper);

        var notice = new TieCommentReplyNotice();
        notice.setTieCommentUserId(comment.getId());
        notice.setTieCommentReplyId(r.getTieCommentId());
        this.tieCommentReplyNoticeMapper.insert(notice);

        return Result.success();
    }
}


